'use strict';

exports.main = async (event, context) => {
  const { file, fileName, fileType = 'image' } = event;
  
  if (!file || !fileName) {
    return { code: 400, msg: '缺少文件或文件名' };
  }

  try {
    // 生成唯一文件名
    const timestamp = Date.now();
    const randomStr = Math.random().toString(36).substr(2, 9);
    const fileExtension = fileName.split('.').pop();
    const cloudPath = `chat/${fileType}s/${timestamp}_${randomStr}.${fileExtension}`;

    // 如果file是base64字符串，需要转换为Buffer
    let fileContent = file;
    if (typeof file === 'string') {
      fileContent = Buffer.from(file, 'base64');
    }

    // 上传文件到云存储
    const result = await uniCloud.uploadFile({
      cloudPath: cloudPath,
      fileContent: fileContent
    });

    if (result.fileID) {
      return {
        code: 200,
        msg: '上传成功',
        data: {
          fileID: result.fileID,
          url: result.fileID,
          cloudPath: cloudPath
        }
      };
    } else {
      return { code: 500, msg: '上传失败' };
    }
  } catch (error) {
    console.error('文件上传失败:', error);
    return { code: 500, msg: '上传失败', error: error.message };
  }
};
